package com.meterhuang.thread.queue;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 同步队列
 *
 * @author meterhuang
 * @date 2021/09/10 10:53
 */
@Slf4j
public class SynchronousQueueTest {

	public static void main(String[] args) {
		SynchronousQueue<Object> synchronousQueue = new SynchronousQueue<>();
		for (int i = 0; i < 3; i++) {
			int iFinal = i;
			new Thread(() -> {
				try {
					log.info("{}", Thread.currentThread().getName() + " put");
					///synchronousQueue.put(iFinal);
					// offer等待指定时长后退出
					synchronousQueue.offer(iFinal, 3000, TimeUnit.MILLISECONDS);
					log.info("{}", Thread.currentThread().getName() + " put " + iFinal);
				} catch (Exception e) {
					e.printStackTrace();
				}
			},"Put"+i).start();
		}

		for (int i = 0; i < 3; i++) {
			new Thread(() -> {
				try {
					log.info("{}", Thread.currentThread().getName() + " take");
					Object take = synchronousQueue.take();
					log.info("{}", Thread.currentThread().getName() + " take "+take);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			},"Take"+i).start();
		}
	}

}
